package com.zziq.cloudpicturebank.manager.upload.template;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.zziq.cloudpicturebank.config.CosClientConfig;
import com.zziq.cloudpicturebank.exception.BusinessException;
import com.zziq.cloudpicturebank.exception.ErrorCode;
import com.zziq.cloudpicturebank.manager.upload.CosManager;
import com.zziq.cloudpicturebank.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 文件上传、下载管理器
 */
@Slf4j
public abstract class PictureUploadTemplate {
  
    @Resource
    private CosClientConfig cosClientConfig;
  
    @Resource  
    private CosManager cosManager;

    /**
     * 处理文件来源
     * @param inputSourse
     * @param file
     */
    protected abstract void processFile(Object inputSourse,File file) throws IOException;

    /**
     * 获取原始文件名成
     * @param inputSourse
     * @return
     */
    protected abstract String getOriginalFilename(Object inputSourse);

    /**
     * 校验图片合法性,
     * @param inputSourse
     */
    protected abstract String validPicture(Object inputSourse);

    /**
     * 上传图片
     * @param inputSourse 输入源
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public UploadPictureResult uploadPicture(Object inputSourse, String uploadPathPrefix) {
        // 1、校验图片,并获取到图片后缀
        String fileSuffix = validPicture(inputSourse);
        // 2、拼接图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originFilename = getOriginalFilename(inputSourse);
        if (originFilename == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件名不能为空");
        }
        //获取到文件后缀
        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,fileSuffix);
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
        File file = null;
        try {
            // 3.创建临时文件
            file = File.createTempFile(uploadPath, null);
            //4.处理文件来源
            processFile(inputSourse,file);
            //5.上传图片到对象云存储
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            //6.处理返回结果 并返回结果
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if (CollectionUtil.isNotEmpty(objectList)) {
                //获取压缩后得到的文件信息
                CIObject compressCiObject = objectList.get(0);
                //缩略图默认压缩图
                CIObject thumbnainCiObject = compressCiObject;
                //如果需要可以缩略
                if (objectList.size() > 1){
                    //获取缩略图对象
                    thumbnainCiObject = objectList.get(1);
                }
                //封装处理图片后的返回结果
                return buildResult(originFilename, compressCiObject,
                        thumbnainCiObject, uploadPath,imageInfo);
            }
            return buildResult(imageInfo, originFilename, file, uploadPath);
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            //7.删除临时文件
            this.deleteTempFile(file);
        }
    }

    /**
     * 封装返回结果(压缩图+缩略图)
     * @param originFilename 原始文件名称
     * @param compressCiObject 压缩图对象
     * @param thumbnainCiObject 缩略图对象
     * @return
     */
    private UploadPictureResult buildResult(String originFilename,CIObject compressCiObject,CIObject thumbnainCiObject,String uploadPath,ImageInfo imageInfo){
        // 封装返回结果
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = compressCiObject.getWidth();
        int picHeight = compressCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressCiObject.getFormat());
        uploadPictureResult.setPicSize(compressCiObject.getSize().longValue());
        //设置上传的压缩图（原图）的url
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressCiObject.getKey());
        //设置缩略图的url
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnainCiObject.getKey());
        ////设置原图的url
        uploadPictureResult.setOriginUrl(cosClientConfig.getHost() + "/" + uploadPath);
        return uploadPictureResult;
    }

    /**
     * 封装返回结果
     * @param imageInfo
     * @param originFilename
     * @param file
     * @param uploadPath
     * @return
     */
    @Deprecated
    private UploadPictureResult buildResult(ImageInfo imageInfo, String originFilename, File file, String uploadPath) {
        // 封装返回结果
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        uploadPictureResult.setPicColor(imageInfo.getAve());
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        return uploadPictureResult;
    }

    /**
     * 删除临时文件
     */
    public void deleteTempFile(File file) {
        if (file == null) {
            return;
        }
        // 删除临时文件
        boolean deleteResult = file.delete();
        if (!deleteResult) {
            log.error("file delete error, filepath = {}", file.getAbsolutePath());
        }
    }
}
